package com.base.cn.platform.os.common.classes;

import com.base.cn.platform.os.common.constants.CacheConstants;
import com.base.cn.platform.os.common.j2cache.CustomCacheChannel;
import com.base.cn.platform.os.common.j2cache.J2CacheRegion;
import com.base.cn.platform.os.common.utils.ObjectUtils;
import com.base.cn.platform.os.common.utils.StringUtils;
import com.base.cn.platform.os.common.utils.web.LoginUtil;
import com.base.cn.platform.os.service.course.classes.member.ClassesMemberService;
import com.base.cn.platform.os.service.course.classes.topic.ClassesTopicService;
import com.base.cn.platform.os.service.manage.join.UserRoleService;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.ui.Model;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.PostConstruct;
import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 文 件 名:OpLogAop
 * 创 建 人:hackeridear
 * 创建日期:2018-12-06
 * 描   述:OpLogAop
 * 修 改 人:
 * 修改日期:
 * 版 本 号:v 1.0.0
 */
@Slf4j
@Component
@Aspect
public class TeacherDataIsolationAop {

    @Autowired
    public LoginUtil loginUtil;
    @Autowired
    public UserRoleService userRoleService;
    @Autowired
    public ClassesMemberService classesMemberService;
    @Autowired
    private CustomCacheChannel customCacheChannel;
    @Autowired
    ClassesTopicService classesTopicService;


    private static ThreadLocal<Long> runTime = ThreadLocal.withInitial(() -> 0L);

    @PostConstruct
    public void init(){
        log.info("-----------------------------");
    }

    @Pointcut("@annotation(TeacherDataIsolation)")
    public void pointCutMethod(){}

    @Before( "@annotation(teacherDataIsolation)")
    public void doBefore(JoinPoint joinPoint,TeacherDataIsolation teacherDataIsolation){
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        BigDecimal teacherId = loginUtil.getLoginUserTeacherId(request);
        if(teacherId.compareTo(new BigDecimal(0)) !=0){
            BigDecimal userId = loginUtil.getLoginUserId(request);
            List<Map<String, Object>> userRoleListByUserId = userRoleService.findUserRoleListByUserId(userId);
            if(ObjectUtils.isNotEmpty(userRoleListByUserId)){
                for(Map userRole:userRoleListByUserId){
                    //判断是否拥有讲师权限
                        if(new BigDecimal(userRole.get("id").toString()).compareTo(new BigDecimal(5))==0){
                            //获取讲师加入班级
                            String ids =   (String)customCacheChannel.get(J2CacheRegion.ONE_DAY_REGION.getValue(), CacheConstants.USER_TEACHER_CLASSES_KEY_IDS+teacherId.toString()).getValue();
                            if(StringUtils.isEmpty(ids)){
                                Map<String, Object> condition = Collections.singletonMap("memberId", teacherId);
                                List<Map<String, Object>> classesTeacherPersonalList = classesMemberService.findClassesMemberList(condition,false,1,3);
                                if(ObjectUtils.isNotEmpty(classesTeacherPersonalList)){
                                    ids =   classesTeacherPersonalList.stream().map(e-> e.get("classesId").toString()).collect(Collectors.joining(","));
                                    customCacheChannel.set(J2CacheRegion.ONE_DAY_REGION.getValue(), CacheConstants.USER_TEACHER_CLASSES_KEY_IDS+teacherId.toString(),ids);
                                }
                            }
                            Object[] args = joinPoint.getArgs();
                            int type = teacherDataIsolation.type();
                            if(args.length>1&&args[1] instanceof  java.util.Map) {

                                if (StringUtils.isNotEmpty(ids)) {
                                    if (type == 2|| type==5) {
                                        ((Map) args[1]).put("classIds", ids);
                                        if (type == 5) {
                                            ((Map) args[1]).put("createUserId", userId);
                                        }
                                    } else if(type==4){
                                        Map<String, Object> classesTopic  =new HashMap<>();
                                        classesTopic.put("classesIds",ids);
                                        List<Map<String, Object>> classesTopicList = classesTopicService.findClassesTopicList(classesTopic, null, null, false, false, false);
                                        if(ObjectUtils.isNotEmpty(classesTopicList)){
                                            String topicIds =   classesTopicList.stream().map(e-> e.get("id").toString()).collect(Collectors.joining(","));
                                            ((Map) args[1]).put("topicIds",topicIds);
                                        }else{
                                            ((Map) args[1]).put("topicIds",0);
                                        }
                                    }else {
                                        ((Map) args[1]).put("ids", ids);
                                    }

                                } else {
                                    if (type == 2) {
                                        ((Map) args[1]).put("classIds", 0);
                                    } else if(type==4){
                                        ((Map) args[1]).put("topicIds", 0);
                                    } else {
                                        ((Map) args[1]).put("ids", 0);
                                    }

                                }
                            }else{
                                 if(type==3){
                                    if(args[0] instanceof Model &&(int)args[3]==1){
                                        if(StringUtils.isNotEmpty(ids)){
                                            ((Model)args[0]).addAttribute("ids",ids);
                                        }
                                    }
                                }else  if(type==6){
                                     ((Model)args[0]).addAttribute("isHide",true);
                                 }
                            }
                        }
                }
            }
        }
    }
    @Around("pointCutMethod()")
    public Object recordOperateLog(ProceedingJoinPoint point) {
        Object result = null;
        long beginTime = System.currentTimeMillis();
        try {
            // 执行方法
            result = point.proceed();
        } catch (Throwable e) {
            e.printStackTrace();
        }
        // 执行时长(毫秒)
        long time = System.currentTimeMillis() - beginTime;
        runTime.set(time);
        return result;
    }
}
